package com.example.input;

import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.dto.User;
import com.example.repositories.UserRepository;
import com.example.utils.AccountAutoTipTextWatcher;
import com.example.utils.HideKeyBordTextWatcher;

public class LoginActivity extends AppCompatActivity {

    private UserRepository userRepository;

    private User userInDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        RadioGroup loginMethod = findViewById(R.id.loginMethod);

        EditText passwordView = findViewById(R.id.password);
        TextView passwordLabel = findViewById(R.id.passwordLabel);
        CheckBox rememberMe = findViewById(R.id.rememberMe);
        Button buttonInPassword = findViewById(R.id.buttonInPassword);
        EditText phoneNumberEditText = findViewById(R.id.phoneNumber);

        phoneNumberEditText.addTextChangedListener(new HideKeyBordTextWatcher(this,11,phoneNumberEditText));

        userRepository = new UserRepository(this);

        phoneNumberEditText.addTextChangedListener(new AccountAutoTipTextWatcher(11,account->{
            userInDB = userRepository.findByAccount(account);
            if (userInDB!=null) {
                rememberMe.setChecked(true);
                passwordView.setText(userInDB.getPassword());
            }
        }));

        loginMethod.setOnCheckedChangeListener((group, checkedId) -> {
            if(checkedId==R.id.loginByPassword){
                passwordLabel.setText("登录密码:");
                passwordView.setHint("请输入密码");
                rememberMe.setVisibility(VISIBLE);
                buttonInPassword.setText("忘记密码");
            }else if(checkedId==R.id.loginByVerificationCode){
                passwordLabel.setText("验证码:");
                passwordView.setHint("请输入验证码");
                rememberMe.setVisibility(INVISIBLE);
                buttonInPassword.setText("发送验证码");
            }
        });

        ActivityResultLauncher<Intent> findPasswordLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), (ActivityResult res) -> {
            if (res.getResultCode() == RESULT_OK) {
                loginMethod.check(R.id.loginByPassword);
                if (res.getData() != null) {
                    // 获得修改之后的新密码
                    passwordView.setText(res.getData().getStringExtra("newPassword"));
                }
            }
        });

        buttonInPassword.setOnClickListener(view->{

            if (loginMethod.getCheckedRadioButtonId()==R.id.loginByPassword) {

                Intent intent = new Intent(this, FindPasswordBackActivity.class);
                intent.putExtra("phoneNumber",phoneNumberEditText.getEditableText().toString());
                findPasswordLauncher.launch(intent);

            }else if(loginMethod.getCheckedRadioButtonId()==R.id.loginByVerificationCode){
                buttonInPassword.setClickable(false);
                //发送验证码
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                buttonInPassword.setClickable(true);
            }
        });

        loginMethod.check(R.id.loginByPassword);

        SharedPreferences accountPassword = getSharedPreferences("account_password", MODE_PRIVATE);

        findViewById(R.id.login).setOnClickListener(view->{
            if (rememberMe.isChecked()) {

               /* accountPassword.edit()
                        .putString("phoneNumber",phoneNumberEditText.getText().toString())
                        .putString("password",passwordView.getText().toString())
                        .apply();*/
                User user = new User();
                user.setAccount(phoneNumberEditText.getText().toString());
                user.setPassword(passwordView.getText().toString());
                if (userInDB ==null) {

                    userRepository.insert(user);
                }else{
                    userInDB.setPassword(passwordView.getText().toString());
                    userRepository.update(userInDB);
                }


            }

            new AlertDialog.Builder(this)
                    .setTitle("登录成功")
                    .setMessage("确认退出")
                    .setPositiveButton("退出",(DialogInterface dialog, int which)->{
                        finish();
                    }).create().show();
        });

       /* String phoneNumber = accountPassword.getString("phoneNumber", "");
        phoneNumberEditText.setText(phoneNumber);

        passwordView.setText(accountPassword.getString("password",""));*/

        User defaultUser = userRepository.findLatest();

        phoneNumberEditText.setText(defaultUser.getAccount());

        passwordView.setText(defaultUser.getPassword());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        userRepository.close();
    }
}